#include "chatwindow.h"
#include "ui_chatwindow.h"
#include <QDateTime>
#include <QFont>
#include <QColor>
#include <QScrollBar>
#include <QMessageBox>
#include <QFileDialog>
#include <QTextStream>
#include <QDebug>

ChatWindow::ChatWindow(const QString &username, QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::ChatWindow)
    , m_client(new ChatClient(this))
    , m_username(username)
{
    ui->setupUi(this);
    m_client->setUsername(username);
    setupUI();
    
    // 连接信号槽
    connect(m_sendBtn, &QPushButton::clicked, this, &ChatWindow::onSendClicked);
    connect(m_clearBtn, &QPushButton::clicked, this, &ChatWindow::onClearClicked);
    connect(m_saveBtn, &QPushButton::clicked, this, &ChatWindow::onSaveClicked);
    connect(m_messageInput, &QLineEdit::returnPressed, this, &ChatWindow::onReturnPressed);
    
    connect(m_client, &ChatClient::connected, this, &ChatWindow::onConnected);
    connect(m_client, &ChatClient::disconnected, this, &ChatWindow::onDisconnected);
    connect(m_client, &ChatClient::errorOccurred, this, &ChatWindow::onErrorOccurred);
    connect(m_client, &ChatClient::messageReceived, this, &ChatWindow::onMessageReceived);
    
    // 连接到本地服务器
    m_client->connectToServer();
}

ChatWindow::~ChatWindow()
{
    delete ui;
}

void ChatWindow::setupUI()
{
    setWindowTitle(QString("本地聊天 - %1").arg(m_username));
    setMinimumSize(900, 600);
    setStyleSheet("QMainWindow { background-color: #f5f5f5; }"
                  "QLabel { color: #333; }"
                  "QPushButton {"
                  "   background-color: #4CAF50;"
                  "   border: none;"
                  "   color: white;"
                  "   padding: 6px 12px;"
                  "   text-align: center;"
                  "   text-decoration: none;"
                  "   font-size: 12px;"
                  "   border-radius: 4px;"
                  "}"
                  "QPushButton:hover {"
                  "   background-color: #45a049;"
                  "}"
                  "QPushButton:disabled {"
                  "   background-color: #cccccc;"
                  "}"
                  "QPushButton#clearBtn {"
                  "   background-color: #ff9800;"
                  "}"
                  "QPushButton#clearBtn:hover {"
                  "   background-color: #e68900;"
                  "}"
                  "QPushButton#saveBtn {"
                  "   background-color: #2196F3;"
                  "}"
                  "QPushButton#saveBtn:hover {"
                  "   background-color: #0b7dda;"
                  "}"
                  "QLineEdit {"
                  "   padding: 8px;"
                  "   border: 1px solid #ddd;"
                  "   border-radius: 4px;"
                  "   background-color: white;"
                  "}"
                  "QTextEdit {"
                  "   border: 1px solid #ddd;"
                  "   border-radius: 4px;"
                  "}");
    
    // 创建中心部件和主布局
    QWidget *centralWidget = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    
    // 顶部状态栏
    QWidget *statusWidget = new QWidget();
    statusWidget->setStyleSheet("background-color: white; border: 1px solid #ddd; border-radius: 4px; padding: 10px;");
    QHBoxLayout *statusLayout = new QHBoxLayout(statusWidget);
    statusLayout->setContentsMargins(10, 10, 10, 10);
    
    m_usernameLabel = new QLabel(QString("当前用户: %1").arg(m_username));
    m_usernameLabel->setStyleSheet("font-weight: bold; color: #2c3e50; font-size: 14px;");
    
    m_statusLabel = new QLabel("连接中...");
    m_statusLabel->setStyleSheet("color: orange; font-weight: bold;");
    
    statusLayout->addWidget(m_usernameLabel);
    statusLayout->addStretch();
    statusLayout->addWidget(m_statusLabel);
    
    // 聊天显示区域
    QLabel *chatLabel = new QLabel("聊天记录:");
    chatLabel->setStyleSheet("font-weight: bold; color: #2c3e50; margin-top: 10px;");
    
    m_chatDisplay = new QTextEdit();
    m_chatDisplay->setReadOnly(true);
    m_chatDisplay->setStyleSheet("background-color: white; border: 1px solid #ddd; border-radius: 4px; padding: 10px;");
    m_chatDisplay->setMinimumHeight(400);
    
    // 输入和按钮区域
    QWidget *inputWidget = new QWidget();
    inputWidget->setStyleSheet("background-color: white; border: 1px solid #ddd; border-radius: 4px; padding: 10px;");
    QHBoxLayout *inputLayout = new QHBoxLayout(inputWidget);
    inputLayout->setContentsMargins(10, 10, 10, 10);
    
    m_messageInput = new QLineEdit();
    m_messageInput->setPlaceholderText("输入消息，按Enter发送...");
    m_messageInput->setEnabled(false);
    
    m_sendBtn = new QPushButton("发送");
    m_sendBtn->setFixedSize(80, 30);
    m_sendBtn->setEnabled(false);
    
    m_clearBtn = new QPushButton("清空记录");
    m_clearBtn->setObjectName("clearBtn");
    m_clearBtn->setFixedSize(80, 30);
    
    m_saveBtn = new QPushButton("保存记录");
    m_saveBtn->setObjectName("saveBtn");
    m_saveBtn->setFixedSize(80, 30);
    
    inputLayout->addWidget(m_messageInput);
    inputLayout->addWidget(m_sendBtn);
    inputLayout->addWidget(m_clearBtn);
    inputLayout->addWidget(m_saveBtn);
    
    // 组装主布局
    mainLayout->addWidget(statusWidget);
    mainLayout->addWidget(chatLabel);
    mainLayout->addWidget(m_chatDisplay);
    mainLayout->addWidget(inputWidget);
    
    setCentralWidget(centralWidget);
}

void ChatWindow::onSendClicked()
{
    QString content = m_messageInput->text().trimmed();
    if (content.isEmpty()) return;
    
    // 发送消息
    m_client->sendMessage(content);
    
    // 清空输入框
    m_messageInput->clear();
}

void ChatWindow::onClearClicked()
{
    if (QMessageBox::question(this, "确认清空", "确定要清空当前聊天记录吗?") == QMessageBox::Yes) {
        m_chatDisplay->clear();
    }
}

void ChatWindow::onSaveClicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, "保存聊天记录", "", "文本文件 (*.txt)");
    if (fileName.isEmpty()) return;
    
    QFile file(fileName);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream out(&file);
        out << m_chatDisplay->toPlainText();
        file.close();
        QMessageBox::information(this, "保存成功", "聊天记录已成功保存");
    } else {
        QMessageBox::warning(this, "保存失败", "无法保存聊天记录");
    }
}

void ChatWindow::onConnected()
{
    updateStatus("已连接", false);
    m_messageInput->setEnabled(true);
    m_sendBtn->setEnabled(true);
    m_messageInput->setFocus();
}

void ChatWindow::onDisconnected()
{
    updateStatus("已断开连接", true);
    m_messageInput->setEnabled(false);
    m_sendBtn->setEnabled(false);
}

void ChatWindow::onErrorOccurred(const QString &error)
{
    updateStatus("错误: " + error, true);
    QMessageBox::warning(this, "连接错误", error);
}

void ChatWindow::onMessageReceived(const Message &message)
{
    // 特殊处理系统消息
    if (message.username() == "系统") {
        appendSystemMessage(message);
        return;
    }
    
    // 判断是否为自己发送的消息
    // 修复：确保正确比较用户名
    bool isSelf = (message.username() == m_username);
    
    // 调试信息
    qDebug() << "Received message - From:" << message.username() << "Self:" << m_username << "Is self:" << isSelf;
    
    appendMessage(message, isSelf);
}

void ChatWindow::onReturnPressed()
{
    if (m_client->isConnected()) {
        onSendClicked();
    }
}

void ChatWindow::appendMessage(const Message &message, bool isSelf)
{
    QString timeStr = message.timestamp().toString("HH:mm:ss");
    
    // 创建消息容器div
    QString containerStyle = isSelf ? 
        "text-align: right; margin: 8px 0;" : 
        "text-align: left; margin: 8px 0;";
    
    // 创建气泡样式
    QString bubbleStyle;
    QString usernameStyle = isSelf ? "text-align: right;" : "text-align: left;";
    
    if (isSelf) {
        // 发送的消息样式（绿色气泡，右对齐）
        bubbleStyle = "background-color: #dcf8c6; padding: 10px; border-radius: 8px; "
                     "border-bottom-right-radius: 0;";
    } else {
        // 接收的消息样式（白色气泡，左对齐）
        bubbleStyle = "background-color: #ffffff; padding: 10px; border-radius: 8px; "
                     "border-bottom-left-radius: 0; border: 1px solid #e0e0e0;";
    }
    
    // 构建HTML内容
    QString html = QString(
        "<div style='%1'>"
            "<div style='display: inline-block; text-align: left; max-width: 70%;'>"
                "<div style='font-size: 12px; color: #666; margin-bottom: 4px; %2'>"
                    "<span style='font-weight: bold;'>%3</span> %4"
                "</div>"
                "<div style='%5'>"
                    "%6"
                "</div>"
            "</div>"
        "</div>"
        "<br>").arg(containerStyle)
         .arg(usernameStyle)
         .arg(message.username())
         .arg(timeStr)
         .arg(bubbleStyle)
         .arg(message.content().toHtmlEscaped());
    
    // 插入HTML内容并滚动到底部
    m_chatDisplay->insertHtml(html);
    m_chatDisplay->verticalScrollBar()->setValue(m_chatDisplay->verticalScrollBar()->maximum());
}

void ChatWindow::appendSystemMessage(const Message &message)
{
    QString html = QString("<div style='text-align: center; margin: 10px 0;'>"
                          "<span style='background-color: #e0e0e0; color: #666; padding: 4px 10px; border-radius: 12px; font-size: 12px;'>"
                          "%1"
                          "</span>"
                          "</div>").arg(message.content().toHtmlEscaped());
    
    m_chatDisplay->insertHtml(html);
    // 自动滚动到底部
    m_chatDisplay->verticalScrollBar()->setValue(m_chatDisplay->verticalScrollBar()->maximum());
    
    // 添加换行以确保消息之间有适当的间距
    m_chatDisplay->insertHtml("<br>");
}

void ChatWindow::updateStatus(const QString &status, bool isError)
{
    m_statusLabel->setText(status);
    m_statusLabel->setStyleSheet(isError ? "color: red;" : "color: green;");
}

